package com.exam.api.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.exam.api.common.exception.GlobalException;
import com.exam.api.common.utils.FindUtil;
import com.exam.api.common.utils.ListDiffUtil;
import com.exam.api.modules.system.domain.TblRole;
import com.exam.api.modules.system.domain.TblUserRole;
import com.exam.api.modules.system.mapper.TblUserRoleMapper;
import com.exam.api.modules.system.vo.UserRoleVO;
import com.exam.api.modules.system.service.TblRoleService;
import com.exam.api.modules.system.service.TblUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色逻辑接口类实现类
 *
 * @author bcheng
 */
@Slf4j
@Service
public class TblUserRoleServiceImpl extends ServiceImpl<TblUserRoleMapper, TblUserRole> implements TblUserRoleService {

    @Resource
    private TblRoleService tblRoleService;

    @Override
    public Map<Long, List<UserRoleVO>> mapUserRoleList(Collection<Long> userIds) {
        if (CollUtil.isEmpty(userIds)){
            return Map.of();
        }
        return baseMapper.listUserRole(userIds)
                .stream()
                .collect(Collectors.groupingBy(UserRoleVO::getUserId));
    }


    @Override
    public List<TblUserRole> listUserRoles(Long userId) {
        List<TblUserRole> list = lambdaQuery()
                .eq(TblUserRole::getUserId, userId)
                .list();
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRole(Long userId, List<Long> roleIds) {
        //1. 查询出所有的角色
        List<TblRole> roles = tblRoleService.listByIds(roleIds);
        Set<Long> originalList = lambdaQuery()
                .eq(TblUserRole::getUserId, userId)
                .select(TblUserRole::getRoleId)
                .list()
                .stream()
                .map(TblUserRole::getRoleId)
                .collect(Collectors.toSet());
        //2. 找出新增的
        List<Long> added = ListDiffUtil.findAdded(originalList, roleIds, (item) -> item);
        if (CollUtil.isNotEmpty(added)) {
            List<TblUserRole> addedList = added.stream()
                    .map(roleId -> {
                        // 查询出角色信息
                        TblRole role = FindUtil.findFirst(roles, TblRole::getRoleId, roleId)
                                .orElseThrow(() -> new GlobalException("角色不存在"));
                        TblUserRole userRole = new TblUserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(role.getRoleId());
                        return userRole;
                    }).toList();
            saveBatch(addedList);
            log.info(" <<<=== 新增用户角色关系 用户id : {} 角色id： {}", userId, added);
        }
        //3. 找出删除的
        List<Long> deleted = ListDiffUtil.findDeleted(originalList, roleIds, (item) -> item);
        if (CollUtil.isNotEmpty(deleted)) {
            lambdaUpdate()
                    .eq(TblUserRole::getUserId, userId)
                    .in(TblUserRole::getRoleId, deleted)
                    .remove();
            log.info(" <<<=== 删除角色菜单关系 用户id : {} 角色id： {}", userId, deleted);
        }
    }
}
